//
//  SponsorViewController.swift
//  d11
//
//  Created by Jar Su on 2/15/20.
//  Copyright © 2020 Tech_001. All rights reserved.
//

import UIKit
import WebKit
import CoreData
class SponsorViewController: BXBaseVC , WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler{
    
    var navigationRightButton: UIButton?
    
    var wkWebView : WKWebView?
    var request : URLRequest?
    var cookies : String?
    var urlString = "https://m.babababar.com/home/sponsors?app=1"
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.init("F8F9FB")
        //设置导航栏右边按钮
        configureNavigationRightButton()
        //设置导航栏图片标题
        navigationItemTitleView()
        
        notificationCenterListener()
        
        if(GlobalInfo.sponsorUrl == "" || GlobalInfo.sponsorUrl == nil){
            urlString = "https://m.71xiang.com/home/sponsors?app=1"
        }else{
            urlString = GlobalInfo.sponsorUrl ?? "https://m.71xiang.com/home/sponsors?app=1"
        }
        request = URLRequest(url: URL(string: urlString)!)
        
        
       //创建
          request?.httpShouldHandleCookies = true
          var array = [Any]()
          for cookie: HTTPCookie in HTTPCookieStorage.shared.cookies! {
              if (cookie.name as NSString).range(of: "'").location != NSNotFound {
                  continue
              }
            let value: String = "\(cookie.name)=\(cookie.value)"
//                array.append(value)
//                print("\(cookie.domain)========\(GlobalInfo.apiDomain)")
            if(GlobalInfo.apiDomain.contains(cookie.domain)){
                let value: String = "\(cookie.name)=\(cookie.value)"
                array.append(value)
            }
            
          }
       
        cookies = (array as NSArray).componentsJoined(by: ";")
        print("=====cookie:\(cookies)")
        let cookieScript = WKUserScript.init(source: cookies!, injectionTime: .atDocumentStart, forMainFrameOnly: false)
        let userContent = WKUserContentController.init()
        userContent.addUserScript(cookieScript)
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.allowsInlineMediaPlayback = true
        wkWebConfig.userContentController = userContent
        wkWebView = WKWebView.init(frame: CGRect.init(x: 0, y: kNavigationBarHeight, width: ScreenWidth, height: ScreenHeight), configuration: wkWebConfig)
        request?.setValue(cookies, forHTTPHeaderField: "Cookie")
        wkWebView?.navigationDelegate = self
        wkWebView?.uiDelegate = self
            
        self.view.addSubview(wkWebView!)
        wkWebView?.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets(top: kNavigationBarHeight, left: 0, bottom: 0, right: 0))
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationRightButton?.isHidden = UserHelper.getLoginStatus()
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        wkWebView?.load(request!)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationBarDefault()
        self.navigationRightButton?.isHidden = true
    }
    
    func notificationCenterListener() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.userLoginSucceed), name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_SUCCEED), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.userLoginOut), name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_OUT), object: nil)
    }
    
    @objc func userLoginSucceed() {
        DispatchQueue.main.async {
            self.navigationRightButton?.isHidden = true
        }
    }
    @objc func userLoginOut() {
        DispatchQueue.main.async {
            self.navigationRightButton?.isHidden = false
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_SUCCEED), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_OUT), object: nil)
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
         dismissLoadHUD()
     }
     func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
         showLoadHUD(title: "")
     }
  
    // 配置顶部登录按钮
    func configureNavigationRightButton() {
        // 登录按钮
        self.navigationRightButton = UIButton.init(frame: CGRect(x: self.view.frame.width - 54, y: 0, width: 54, height: 28))
        // 渐变色
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.navigationRightButton!.bounds
        gradientLayer.colors = [
            UIColor.init("FBCE81")!.cgColor,
            UIColor.init("FF914A")!.cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        self.navigationRightButton!.layer.insertSublayer(gradientLayer, at: 0)
        self.navigationRightButton!.clipRectCorner(direction: [UIRectCorner.topLeft,UIRectCorner.bottomLeft], cornerRadius: 14)
        self.navigationRightButton!.setTitle("  登录", for: UIControl.State.normal)
        self.navigationRightButton!.setTitleColor(UIColor.white, for: UIControl.State.normal)
        self.navigationRightButton!.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
        self.navigationRightButton!.addTarget(self, action: #selector(navigationRightButtonClick), for: UIControl.Event.touchUpInside)
        self.navigationController?.navigationBar.addSubview(self.navigationRightButton!)
        self.navigationRightButton!.snp.makeConstraints { (make) in
            make.centerY.right.equalToSuperview()
            make.width.equalTo(54)
            make.height.equalTo(28)
        }
    }
    
    @objc func navigationRightButtonClick(){
        LoginViewController.loginIfNeedController(currentController: self) {
            
            print("登录成功")
        }
    }
    
// MARK: -- WKUIDelegate
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("======Url:\(navigationAction.request.url?.absoluteString)")
        print("======head:\(navigationAction.request.allHTTPHeaderFields)")
        
        if(navigationAction.request.url?.absoluteString.contains("login") ?? false){
            PopWindowHelper.actionToLogin()
             decisionHandler(.cancel)
        }else{
            decisionHandler(.allow)
        }
    }
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
           if navigationAction.targetFrame == nil {
               if let url = navigationAction.request.url{
                   if url.description.lowercased().range(of: "http://") != nil || url.description.lowercased().range(of: "https://") != nil  {
                    
                    print("URL====\(url.absoluteString)")
                    var headers : [String : String] = navigationAction.request.allHTTPHeaderFields ?? [:]
                        headers.updateValue(cookies ?? "", forKey: "Cookie")
                    headers.updateValue("no-referrer-when-downgrade", forKey: "Referer")
                        var request = navigationAction.request
                        request.allHTTPHeaderFields = headers
                        webView.load(request)
                   
                   }
               }
           }
           return nil
       }
    
// MARK: -- WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
}
